<template>
    <div class="ma-content-block lg:flex justify-between p-4">
        <div class="app-container">
            <div class="container-header">
                <div class="container-header-tr">
                    <div
                        class="mr20"
                        style="display: flex; align-items: center"
                    >
                        <span class="s1 mr10">手机号码</span>
                        <a-input
                            style="flex: 1"
                            v-model="tableModel.searchForm.system_phonenumber"
                            placeholder="手机号码"
                        />
                    </div>
                    <div
                        class="mr20"
                        style="display: flex; align-items: center"
                    >
                        <span class="s1 mr10">设备名称</span>
                        <a-input
                            style="flex: 1"
                            v-model="tableModel.searchForm.mobile_name"
                            placeholder="设备名称"
                        />
                    </div>
                    <div style="display: flex; align-items: center">
                        <span class="s1 mr10">{{
                            $t('basics.sendOrNot')
                        }}</span>
                        <a-select
                            style="width: 120px"
                            class="mr20"
                            v-model="tableModel.searchForm.can_send"
                            :placeholder="$t('basics.sendOrNot')"
                        >
                            <a-option
                                :label="$t('basics.canSend')"
                                :value="1"
                            ></a-option>
                            <a-option
                                :label="$t('basics.notSend')"
                                :value="0"
                            ></a-option>
                        </a-select>
                    </div>
                    <a-button class="mr20 mb10" type="primary" @click="getList">
                        <icon-search class="mr6" />
                        {{ $t('basics.search') }}
                    </a-button>
                    <a-button
                        class="mr20 mb10"
                        type="secondary"
                        @click="resetButton"
                    >
                        <icon-refresh class="mr6" />
                        {{ $t('basics.reset') }}
                    </a-button>
                    <a-button
                        class="mr20 mb10"
                        type="primary"
                        @click="openModal('setUserPhone')"
                    >
                        {{ $t('basics.assignNumbers') }}
                    </a-button>
                    <a-button
                        class="mr20 mb10"
                        type="primary"
                        @click="openModal('unbindPhone')"
                    >
                        {{ $t('basics.unbindPhoneNumber') }}
                    </a-button>
                    <a-button
                        class="mr20 mb10"
                        type="primary"
                        @click="openModal('limit_num_of_con')"
                    >
                        {{ $t('basics.limitNumOfCon') }}
                    </a-button>
                    <a-button
                        class="mr20 mb10"
                        type="primary"
                        status="danger"
                        @click="openModal('delPhone')"
                    >
                        {{ $t('basics.delPhone') }}
                    </a-button>
                    <a-button class="mr20 mb10" type="primary" @click="reset">
                        {{ $t('basics.resetTimes') }}
                    </a-button>
                    <!-- <div @click="setUserPhone" class="btn mb10 mr20">
                        {{ $t('basics.assignNumbers') }}
                    </div>
                    <div @click="reset" class="btn">
                        {{ $t('basics.resetTimes') }}
                    </div> -->
                </div>
                <div class="container-content-table mt10">
                    <a-table
                        ref="table"
                        :stripe="true"
                        :columns="tableModel.columns"
                        :data="tableModel.list"
                        :loading="tableModel.loading"
                        :row-selection="tableModel.rowSelection"
                        v-model:selectedKeys="tableModel.selectedKeys"
                        row-key="id"
                        @selection-change="getRowData"
                        :pagination="false"
                    >
                        <template #is_online="{ record }">
                            <div>
                                <a-link v-if="record.is_online" status="success"
                                    >在线</a-link
                                >
                                <a-link v-else status="danger">离线</a-link>
                            </div>
                        </template>
                        <template #last_send_time="{ record }">
                            <div>
                                {{
                                    record.last_send_time
                                        ? $common.formatDate(
                                              new Date(
                                                  record.last_send_time * 1000
                                              )
                                          )
                                        : ''
                                }}
                            </div>
                        </template>

                        <template #bind_time="{ record }">
                            <div>
                                {{
                                    record.bind_time
                                        ? $common.formatDate(
                                              new Date(record.bind_time * 1000)
                                          )
                                        : ''
                                }}
                            </div>
                        </template>
                        <template #last_online_time="{ record }">
                            <div>
                                {{
                                    record.last_online_time
                                        ? $common.formatDate(
                                              new Date(
                                                  record.last_online_time * 1000
                                              )
                                          )
                                        : ''
                                }}
                            </div>
                        </template>
                        <template #can_send="{ record }">
                            <div>
                                <a-popconfirm
                                    @ok="statusChange(record)"
                                    :content="
                                        $t('basics.confirmEdit') +
                                        (record.can_send == 1
                                            ? $t('basics.offTxt')
                                            : $t('basics.openTxt')) +
                                        $t('basics.whatTxt')
                                    "
                                >
                                    <a-switch
                                        :beforeChange="handleChangeIntercept"
                                        v-model="record.can_send"
                                        :checked-value="1"
                                        :unchecked-value="0"
                                    />
                                </a-popconfirm>
                            </div>
                        </template>
                    </a-table>
                    <div
                        class="_crud-footer mt-3 text-right"
                        ref="crudFooterRef"
                    >
                        <a-pagination
                            :total="tableModel.total"
                            show-total
                            show-jumper
                            show-page-size
                            @page-size-change="getList"
                            @change="getList"
                            v-model:current="tableModel.page"
                            :page-size-options="[10, 20, 50, 100]"
                            :default-page-size="100"
                            v-model:page-size="tableModel.pageSize"
                            style="display: inline-flex"
                        />
                    </div>
                </div>
            </div>
            <a-modal
                v-model:visible="form.visible"
                :render-to-body="false"
                :footer="false"
            >
                <template #title> {{ $t('basics.assignNumbers') }} </template>
                <a-form
                    :model="form.formParams"
                    ref="formRef"
                    :rules="form.rules"
                >
                    <a-form-item
                        field="username"
                        :label="$t('basics.userName')"
                        label-col-flex="80px"
                        validate-trigger="blur"
                    >
                        <a-input
                            style="width: 100%; margin-right: 20px"
                            v-model="form.formParams.username"
                            :placeholder="$t('basics.textAcc')"
                        />
                    </a-form-item>
                </a-form>
                <div class="dialog-foot">
                    <a-button class="mr20 c0" @click="cancle">{{
                        $t('basics.concel')
                    }}</a-button>
                    <a-button class="mr20" type="primary" @click="confirm">{{
                        $t('basics.sure')
                    }}</a-button>
                </div>
            </a-modal>
            <a-modal
                v-model:visible="form.unbindPhoneVisible"
                :render-to-body="false"
                :footer="false"
            >
                <template #title>{{ $t('basics.unbindPhoneNumber') }}</template>
                <div>{{ $t('basics.unbindOrNot') }}</div>
                <div class="dialog-foot">
                    <a-button class="mr20 c0" @click="cancle">{{
                        $t('basics.concel')
                    }}</a-button>
                    <a-button
                        class="mr20"
                        type="primary"
                        @click="unbindPhoneRequest"
                        >{{ $t('basics.sure') }}</a-button
                    >
                </div>
            </a-modal>
            <a-modal
                v-model:visible="form.delPhoneVisible"
                :render-to-body="false"
                :footer="false"
            >
                <template #title>{{ $t('basics.delPhone') }}</template>
                <div>{{ $t('basics.delOrNot') }}</div>
                <div class="dialog-foot">
                    <a-button class="mr20 c0" @click="cancle">{{
                        $t('basics.concel')
                    }}</a-button>
                    <a-button class="mr20" type="primary" @click="delPhone">{{
                        $t('basics.sure')
                    }}</a-button>
                </div>
            </a-modal>
            <a-modal
                v-model:visible="form.limitNumVisible"
                :render-to-body="false"
                :footer="false"
            >
                <template #title> {{ $t('basics.limitNumOfCon') }} </template>
                <a-form
                    :model="form.formParams"
                    ref="formRef"
                    :rules="form.rules"
                >
                    <a-form-item
                        field="limitNumOfCon"
                        :label="$t('basics.limitNumOfCon')"
                        label-col-flex="80px"
                        validate-trigger="blur"
                    >
                        <a-input
                            style="width: 100%; margin-right: 20px"
                            v-model="form.formParams.limit_num_of_con"
                            :placeholder="$t('basics.limitNumOfCon')"
                        />
                    </a-form-item>
                </a-form>
                <div class="dialog-foot">
                    <a-button class="mr20 c0" @click="cancle">{{
                        $t('basics.concel')
                    }}</a-button>
                    <a-button class="mr20" type="primary" @click="limitNum">{{
                        $t('basics.sure')
                    }}</a-button>
                </div>
            </a-modal>
        </div>
    </div>
</template>
<script setup>
import { ref, reactive, getCurrentInstance } from 'vue';
import { useI18n } from 'vue-i18n';
import { $request } from '@/utils/request.js';
const { t } = useI18n();
const { proxy } = getCurrentInstance();
const checkedList = ref([]);
const tableModel = reactive({
    loading: true,
    columns: [
        {
            title: t('basics.phoneNumberTxt'),
            dataIndex: 'system_phonenumber'
        },

        {
            title: '是否在线',
            dataIndex: 'is_online',
            slotName: 'is_online'
        },
        // {
        //     title: t('basics.numberOfTimesSendToday'),
        //     dataIndex: 'num_of_send'
        // },
        {
            title: t('basics.numOfCon'),
            dataIndex: 'num_of_con'
        },
        {
            title: t('basics.limitNumOfCon'),
            dataIndex: 'limit_num_of_con'
        },
        {
            title: t('basics.userName'),
            dataIndex: 'username'
        },
        // {
        //     title: t('basics.deviceID'),
        //     dataIndex: 'mobile_id'
        // },
        {
            title: t('basics.deviceName'),
            dataIndex: 'mobile_name'
        },
        {
            title: t('basics.sendOrNot'),
            dataIndex: 'can_send',
            slotName: 'can_send'
        },
        // {
        //     title: t('basics.bindTime'),
        //     dataIndex: 'bind_time',
        //     slotName: 'bind_time'
        // },
        {
            title: t('basics.availableMinutes'),
            dataIndex: 'can_use_minutes',
            slotName: 'can_use_minutes'
        },
        {
            title: t('basics.lastSendingTime'),
            dataIndex: 'last_send_time',
            slotName: 'last_send_time'
        }
        // {
        //     title: '更新时间',
        //     dataIndex: 'updated_at'
        // },

        // {
        //     title: t('basics.controls'),
        //     dataIndex: 'operate',
        //     slotName: 'operate'
        // }
    ],
    selectedKeys: [],
    rowSelection: {
        type: 'checkbox',
        showCheckedAll: true,
        onlyCurrent: false
    },
    list: [],
    page: 1,
    total: 0,
    pageSize: 100,
    searchForm: {}
});

const form = reactive({
    visible: false,
    unbindPhoneVisible: false,
    delPhoneVisible: false,
    limitNumVisible: false,
    formParams: {},
    rules: {
        username: [
            {
                required: true,
                message: t('basics.enterProName')
            }
        ]
    }
});

const reset = async () => {
    tableModel.selectedKeys = [];
    tableModel.page = 1;
    tableModel.pageSize = 20;
    tableModel.loading = true;
    await $request.post('/TcardManage/phonenumberDetail/reset');
    proxy.$message.success(t('basics.resetTimesSuccess'));
    getList();

    tableModel.loading = false;
};

// 获取选择列
const getRowData = (selectedRowKeys) => {
    checkedList.value = selectedRowKeys;
};
// 刷新
const resetButton = async () => {
    tableModel.searchForm = {};
    tableModel.page = 1;
    tableModel.pageSize = 20;
    tableModel.loading = true;
    await getList();
    tableModel.loading = false;
};

// 获取列表数据
const getList = () => {
    let params = {
        ...tableModel.searchForm,
        page: tableModel.page,
        pageSize: tableModel.pageSize
    };
    $request
        .get('/TcardManage/phonenumberDetail/getList', params)
        .then(({ items, pageInfo }) => {
            tableModel.list = items;
            tableModel.total = pageInfo.total;
            tableModel.loading = false;
        });
    cancle();
};
/**开关-确认 */
const statusChange = async (row) => {
    // row.status = Number(!row.status);
    let data = {
        system_phonenumber: row.system_phonenumber,
        can_send: Number(!row.can_send)
    };
    await $request.post('/TcardManage/phonenumberDetail/updateCanSend', data);
    proxy.$message.success(t('basics.successTxt'));
    getList();
};

const handleChangeIntercept = async (newValue) => {
    return false;
};

/**弹窗 */
const openModal = (popName) => {
    if (!checkedList.value.length) {
        proxy.$message.error(t('basics.checkNumber'));
        return;
    }
    if (popName === 'setUserPhone') {
        form.visible = true;
        proxy.$refs['formRef'].resetFields();
    } else if (popName === 'unbindPhone') {
        form.unbindPhoneVisible = true;
    } else if (popName === 'delPhone') {
        form.delPhoneVisible = true;
    } else if (popName === 'limit_num_of_con') {
        form.limitNumVisible = true;
    }
};
/**分配手机-确认按钮 */
const confirm = () => {
    let params = {
        username: form.formParams.username,
        system_phonenumber_array: getPhoneArr()
    };
    $request
        .post('/TcardManage/phonenumberDetail/setUser', params)
        .then((res) => {
            form.visible = false;
            proxy.$message.success(t('basics.allocationSuccess'));
            getList();
        });
};
/**手机号解绑-确定按钮 */
const unbindPhoneRequest = () => {
    let params = {
        system_phonenumber_array: getPhoneArr()
    };
    $request
        .post('/TcardManage/phonenumberDetail/unbind', params)
        .then((res) => {
            form.unbindPhoneVisible = false;
            proxy.$message.success(t('basics.unbindSuccess'));
            getList();
        });
};
/**删除手机号-确定按钮 */
const delPhone = () => {
    let params = {
        system_phonenumber_array: getPhoneArr()
    };
    $request
        .post('/TcardManage/phonenumberDetail/delete', params)
        .then((res) => {
            form.delPhoneVisible = false;
            proxy.$message.success(t('basics.delSuccess'));
            getList();
        });
};
/**最大对话数-确定按钮 */
const limitNum = () => {
    let params = {
        system_phonenumber_array: getPhoneArr(),
        limit_num_of_con: Number(form.formParams.limit_num_of_con)
    };
    $request
        .post('/TcardManage/phonenumberDetail/updateLimitNumOfCon', params)
        .then((res) => {
            form.limitNumVisible = false;
            proxy.$message.success(t('basics.setSuccess'));
            getList();
        });
};
/**返回选中ID的手机号数组 */
const getPhoneArr = () => {
    let arr = [];
    for (let i in checkedList.value) {
        for (let j in tableModel.list) {
            if (checkedList.value[i] === tableModel.list[j].id)
                arr.push(tableModel.list[j].system_phonenumber);
        }
    }
    return arr;
};
const cancle = () => {
    form.visible = false;
    form.unbindPhoneVisible = false;
    form.limitNumVisible = false;
    form.formParams = {};
    resetSelect();
};
/**重置列表多选 */
const resetSelect = () => {
    checkedList.value = [];
    tableModel.selectedKeys = [];
    tableModel.rowSelection = {
        type: 'checkbox',
        showCheckedAll: true,
        onlyCurrent: false
    };
};

getList();
</script>
<style lang="less" scoped>
@import url('@/style/layout.less');
</style>
